package practice;

/**
 * 案例：3个窗口抢100张票【同步锁】
 */
public class Practice1 {

    private static int ticket = 0;

    public static void main(String[] args) {
        MyThread myThread1 = new MyThread("窗口1");
        MyThread myThread2 = new MyThread("窗口2");
        MyThread myThread3 = new MyThread("窗口3");

        myThread1.start();
        myThread2.start();
        myThread3.start();
    }


    private static class MyThread extends Thread{
        @Override
        public void run() {
            while(true){
                // 特点：1、锁默认打开，有一个线程进去，锁自动关闭。
                //      2、里面的全部代码执行完毕，线程出来，锁自动打开
                //      3、锁对象一定要唯一，才能实现锁住的作用
                synchronized (MyThread.class){
                    if (ticket < 100){
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticket ++;
                        System.out.println(getName() + "正在抢票：" + ticket);
                    }
                    else break;
                }
            }
        }

        public MyThread(String name) {
            super(name);
        }
    }


}
